import { useState } from "react";
import { Navigate } from "react-router";
import { useAtomValue, useSetAtom } from "jotai";
import { Button, Form, Input, Select, Spin } from "antd";
import { isAuthPendingAtom, isLoginAtom, loginAtom } from "@/store/user";
import { useMessage } from "@/providers/AntdMessageProvider";

const roles = [
  { label: "管理员", value: "bia_admin" },
  { label: "操作员", value: "Operator" },
];

export default function Login() {
  const [username, setUsername] = useState();
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const login = useSetAtom(loginAtom);
  const isLogin = useAtomValue(isLoginAtom);
  const isAuthPending = useAtomValue(isAuthPendingAtom);
  const message = useMessage();

  function handleLogin() {
    if (!username || !password) {
      return message.error(!username ? "请选择角色" : "请输入密码");
    }
    setLoading(true);
    login({ username, password })
      .then((user) => {
        message.success(`欢迎回来，${user.nickName}!`);
      })
      .catch((error) => {
        if ("msg" in error) {
          message.error(error.msg);
        } else if ("message" in error) {
          message.error(error.message);
        } else {
          message.error("登录遇到错误，请稍后再试！");
        }
      })
      .finally(() => {
        setLoading(false);
      });
  }

  if (isLogin) {
    return <Navigate to="/" replace />;
  }

  if (isAuthPending) {
    return (
      <div className="flex justify-center pt-10">
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div className="flex h-screen items-center justify-center">
      <Form layout="vertical" size="large" className="w-[400px]">
        <Form.Item label="角色">
          <Select
            className="w-40"
            placeholder="请选择角色"
            options={roles}
            value={username}
            onChange={setUsername}
          />
        </Form.Item>
        <Form.Item label="密码">
          <Input
            value={password}
            type="password"
            placeholder="请输入密码"
            onInput={(e) => setPassword((e.target as HTMLInputElement).value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") {
                handleLogin();
              }
            }}
          />
        </Form.Item>
        <Form.Item>
          <Button
            htmlType="button"
            type="primary"
            className="w-full"
            onClick={handleLogin}
            loading={loading}
          >
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}
